<?php
/*
 * @Date: 2021-08-23 09:30:36
 * @LastEditTime: 2021-11-26 17:37:09
 */

declare(strict_types=1);

namespace catchAdmin\monitor\command;

use Carbon\Carbon;
use catchAdmin\basics\model\Company;
use catchAdmin\basics\model\StorageFeeConfig;
use catchAdmin\basics\model\StorageFeeConfigInfo;
use catchAdmin\delivery\common\DeliveryUpsCommon;
use catchAdmin\order\model\OrderDeliver;
use catchAdmin\product\model\Product;
use catchAdmin\settlement\model\StorageFee;
use catchAdmin\settlement\model\StorageProductFee;
use catchAdmin\warehouse\model\WarehouseOrderProducts;
use catchAdmin\warehouse\model\WarehouseStock;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use catcher\Code;
use think\facade\Db;

class UpsTrackingCommand extends Command
{
    protected $pid;

    protected function configure()
    {
        // 指令配置
        $this->setName('catch:UpsTracking')
            ->setDescription('get ups tracking info');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('upsTracking Error Line:' . $e->getLine());
            Log::error('upsTracking Error Code:' . $e->getCode());
            Log::error('upsTracking Error Message:' . $e->getMessage());
            echo $e->getMessage() . "\r\n";
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 执行 command
     *
     * @time 2021年03月02日
     * @return void
     */
    protected function executeCommand()
    {
        $orders = OrderDeliver::whereBetween('delivery_state', '2,4')
            ->field('shipping_code')
            ->where('shipping_name', 'UPS')
            ->where('logistics_type', 1) // 发货物流类型 0-未设置 1-自有物流 2-它有物流
            ->where('delivery_process_status', 2) // // 是否打印面单 1-未打印 2-打印
            ->where('created_at', '>', 1626969600)
            ->order('id', 'desc')
            ->select();
        $ups = new DeliveryUpsCommon([]);
        foreach ($orders as $order) {
            echo 'CODE:' .$order->shipping_code . "\r\n";

            $res = $ups->tracking($order->shipping_code);
            $result = $res;
            if (is_array($result)) {
                $result = $res[0];
            }
            $code = $result->Status->StatusType->Code;
            if ($code == 'D' || $code == 'X') {
                $delivery_state = 5;
            } else {
                $delivery_state = 4;
            }
            $deliver_day = strtotime($result->GMTDate . ' ' . $result->GMTTime);
            OrderDeliver::update(
                [
                    'delivery_state' => $delivery_state,
                    'tracking_info' => json_encode($res),
                    'deliver_day' => $deliver_day,
                    'updated_at' => time()
                ],
                ['shipping_code' => $order->shipping_code]
            );
        }
    }
}
